﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Forest.Lion.Domain.Models;
using Forest.Lion.Domain.Contracts;
using Microsoft.Practices.ServiceLocation;

namespace Forest.Lion.Web.Controllers
{
    public class AuthorizedController : Controller {
        protected readonly IUserServices UserServices;
        private readonly IServiceLocator serviceLocator;
        private string ActionKey;


        public AuthorizedController(IUserServices userServices, IServiceLocator serviceLocator) {
            if (userServices == null)
                throw new ArgumentNullException("userServices");
            this.UserServices = userServices;
            this.serviceLocator = serviceLocator;
        }

        /// <summary>
        /// Retrieves the CurrentUserId as stored in the <see cref="MileageStatsIdentity"/>
        /// </summary>
        /// <remarks>
        /// Using this method requires the user to be authorized.
        /// </remarks>
        protected Guid CurrentUserId {
            get { return this.User.AppIdentity().UserId; }
        }

        private User currentUser;

        /// <summary>
        /// Returns the current user or recovers the user from the <see cref="MileageStatsIdentity"/>.
        /// </summary>
        /// <remarks>
        /// Using this method requires the user to be authorized.
        /// </remarks>
        public User CurrentUser {
            get {
                return this.currentUser ??
                       (this.currentUser = this.UserServices.GetUserFromIdentity(this.User.AppIdentity()));
            }
        }

        // 这里用于动态处理功能授权
        protected override void OnActionExecuting(ActionExecutingContext filterContext) {
            //// 通过处理Action来授权，那些角色能用那些功能
            //ActionKey = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName +
            //           "-" + filterContext.ActionDescriptor.ActionName;

            ////string role = Session["Roles"].ToString();//getting the current role
            //if (ActionKey.Equals("digest-list", StringComparison.OrdinalIgnoreCase) || ActionKey.Equals("digest-add", StringComparison.OrdinalIgnoreCase)) {
            //    if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
            //        string redirectUrl = string.Format("?returnUrl={0}",
            //                filterContext.HttpContext.Request.Url.PathAndQuery);
            //        filterContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl + redirectUrl, true);
            //    }                
            //}
        }


        protected T Using<T>() where T : class {
            var handler = serviceLocator.GetInstance<T>();
            if (handler == null) {
                throw new NullReferenceException("Unable to resolve type with service locator; type " + typeof(T).Name);
            }
            return handler;
        }
    }
}
